import { reactive } from 'vue'
import { TimeBean, TimeRender } from 'tools-time'

const CTween = reactive({
    /**
     * 动画对象管理
     */
    sprite: {
        /**
         * 对象列表
         * {
         *  "name":this
         * }
         */
        list: {} as {
            [key: string]: {
                target: {
                    [key: string]: any
                    bean: TimeBean
                }
                name: string
                to: (options: any) => void
            }
        },
        add(spinfo: any) {
            CTween.sprite.list[spinfo.name] = spinfo
        },
        remove({ name }: any) {
            delete CTween.sprite.list[name]
        }
    },

    /**
     * 开始渲染动画
     */
    run: () => {
        TimeRender.run()
    },

    /**
     * 停止渲染动画
     */
    stop: () => {
        TimeRender.stop()
        CTween.sprite.list = {}
    },

    /**
     * 执行一个动画任务
     * @param name
     * @param options - 只支持基础属性{ x,y,opacity,scale,scaleX,scaleY,rotate,rotateZ } + 动画属性 { time,final,delay,loop }
     */
    to(name: string, options: Partial<TimeBeanParam>) {
        if (Array.isArray(name)) {
            for (let i = 0; i < name.length; i++) {
                CTween.to(name[i], options)
            }
            return
        }
        CTween.sprite.list[name].to(options as any)
    },
    /**
     * 设置值
     * @param name
     * @param options - 只支持基础属性{ x,y,opacity,scale,scaleX,scaleY,rotate,rotateZ }
     */
    set(name: string, options: any) {
        if (Array.isArray(name)) {
            for (let i = 0; i < name.length; i++) {
                CTween.set(name[i], options)
            }
            return
        }
        const info = CTween.sprite.list[name]
        if (info) {
            for (const key in options) {
                //@ts-ignore
                info.target[key] = options[key]
            }
        }
    },
    /**
     * 暂停
     * @param name
     */
    pause(name: any) {
        if (Array.isArray(name)) {
            for (let i = 0; i < name.length; i++) {
                CTween.pause(name[i])
            }
            return
        }
        CTween.sprite.list[name].target.bean.pause()
    },
    /**
     * 反转
     * @param name
     */
    reverse(name: any) {
        if (Array.isArray(name)) {
            for (let i = 0; i < name.length; i++) {
                CTween.reverse(name[i])
            }
            return
        }
        CTween.sprite.list[name].target.bean.reverse()
    },
    /**
     * 继续
     * @param name
     */
    resume(name: any) {
        if (Array.isArray(name)) {
            for (let i = 0; i < name.length; i++) {
                CTween.resume(name[i])
            }
            return
        }
        CTween.sprite.list[name].target.bean.resume()
    }
})

export default CTween
